package com.dyava.commons.token_bucket;

public abstract class TokenBucket {
    public static final String NULL = "__NULL__";

    protected String name;
    protected int limitNum;
    protected int limitDen;

    public TokenBucket(String name, int limitNum, int limitDen) {
        this.name = name;
        this.limitNum = limitNum;
        this.limitDen = limitDen;
    }

    protected int calculateExpectNum(BToken token) {
        long disTime = (System.currentTimeMillis() - token.getLastExecuteTime()); //距离上次毫秒数
        int addNum = (int)(((double)limitNum)*disTime/(limitDen*1000)); //可以添加的次数
        int maxNum = limitNum;

        int expectNum = token.getNum()+addNum;
        if(expectNum<0){  //溢出
            expectNum = maxNum;
        }else if(expectNum > maxNum){ //不能超过maxNum
            expectNum = maxNum;
        }
        return expectNum;
    }

    public abstract boolean limit(Object id);

}
